import React, { useState, useEffect } from 'react';
import { Card, Button, Row, Col, Switch, Typography } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useUserStore } from '../store/user';
import { getProductList, enableProduct } from '../api/product';


const { Title, Paragraph } = Typography;

// 假数据
const products = [
  {
    id: 1,
    name: '牛奶',
    image: 'https://source.unsplash.com/400x400/?milk',
    price: 6.5,
    desc: '新鲜纯牛奶，早餐首选。',
    enabled: true,
  },
  {
    id: 2,
    name: '面包',
    image: 'https://source.unsplash.com/400x400/?bread',
    price: 4.0,
    desc: '松软可口的面包，适合搭配牛奶。',
    enabled: true,
  },
  {
    id: 3,
    name: '鸡蛋',
    image: 'https://source.unsplash.com/400x400/?egg',
    price: 0.8,
    desc: '农家散养鸡蛋，营养丰富。',
    enabled: true,
  },
  {
    id: 4,
    name: '矿泉水',
    image: 'https://source.unsplash.com/400x400/?bottle-water',
    price: 2.0,
    desc: '天然矿泉水，健康饮用。',
    enabled: true,
  },
  {
    id: 5,
    name: '方便面',
    image: 'https://source.unsplash.com/400x400/?instant-noodles',
    price: 3.5,
    desc: '速食方便面，快捷美味。',
    enabled: false,
  },
  {
    id: 6,
    name: '洗发水',
    image: 'https://source.unsplash.com/400x400/?shampoo',
    price: 25.0,
    desc: '清爽去屑洗发水，适合全家使用。',
    enabled: true,
  },
  {
    id: 7,
    name: '篮球鞋',
    image: 'https://source.unsplash.com/400x400/?basketball-shoes',
    price: 299.0,
    desc: '专业篮球鞋，运动舒适，防滑耐磨。',
    enabled: true,
  },
  {
    id: 8,
    name: '哑铃',
    image: 'https://source.unsplash.com/400x400/?dumbbell',
    price: 59.0,
    desc: '家用健身哑铃，锻炼必备。',
    enabled: true,
  },
  {
    id: 9,
    name: 'T恤',
    image: 'https://source.unsplash.com/400x400/?tshirt',
    price: 39.0,
    desc: '纯棉T恤，舒适透气，多色可选。',
    enabled: true,
  },
  {
    id: 10,
    name: '运动短裤',
    image: 'https://source.unsplash.com/400x400/?shorts',
    price: 49.0,
    desc: '速干运动短裤，适合跑步健身。',
    enabled: true,
  },
];

const Home: React.FC = () => {
  const navigate = useNavigate();
  const isLogin = !!localStorage.getItem('token');
  const user = isLogin ? JSON.parse(localStorage.getItem('user') || '{}') : null;
  const isAdmin = user?.isAdmin;
  const [productList, setProductList] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);

  const setUserInfo = useUserStore((state) => state.setUserInfo);

  useEffect(() => {
    getProductList(page, pageSize).then(res => {
      if (res.data && res.data.data && Array.isArray(res.data.data.records)) {
        setProductList(res.data.data.records);
      }
    });
  }, [page, pageSize]);

  // 购买按钮点击事件
  const handleBuy = (product: any) => {
    if (!isLogin) {
      navigate('/login');
      return;
    }
    alert(`已购买：${product.name}`);
  };

  // 管理员上下架商品
  const handleEnable = async (id: number, checked: boolean) => {
    await enableProduct(id, checked);
    setProductList(productList.map(p => p.id === id ? { ...p, enabled: checked } : p));
  };

  return (
    <div style={{ padding: 24 }}>
      {/* 顶部栏 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={2} style={{ margin: 0 }}>皮蛋商场</Title>
        {/* 已登录状态下只显示用户信息和个人中心按钮，不显示登录/注册按钮 */}
        {isLogin && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <img src={user?.avatar} alt="avatar" style={{ width: 32, height: 32, borderRadius: '50%' }} />
            <span>{user?.nickname || user?.username}</span>
            <Button type="link" onClick={() => navigate('/profile')}>个人中心</Button>
          </div>
        )}
      </div>
      <Row gutter={[16, 16]} justify="center">
        {productList.map(product => (
          <Col key={product.id} xs={24} sm={12} md={8} lg={6}>
            <Card
              hoverable
              cover={
                <img
                  alt={product.productName}
                  src={product.productImg || 'https://via.placeholder.com/400x180?text=暂无图片'}
                  style={{ height: 180, objectFit: 'cover' }}
                />
              }
            >
              <Card.Meta
                title={<span>{product.productName || product.name} <span style={{ color: '#faad14', fontWeight: 'bold' }}>￥{product.price}</span></span>}
                description={<>
                  <Paragraph ellipsis={{ rows: 2 }}>{product.desc || product.productDesc}</Paragraph>
                  <div>库存：{product.stock}</div>
                </>}
              />
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
};

export default Home; 